from info import redis_store, constants
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu
from flask import render_template, current_app, session, request, jsonify, g


@index_blu.route('/newslist')
def get_news_list():
    """获取新闻信息
    1.获取数据
    2.对数据校验
    3.判断参数的值
    4.从数据库中查询
    5.返回给前端渲染
    :return:
    """

    # 1.获取数据
    args_dict = request.args
    category_id = args_dict.get('cid', "1")
    page = args_dict.get('page', "1")
    # 每页多少条数据
    per_page = args_dict.get('per_page', constants.HOME_PAGE_MAX_NEWS)

    # 2.对数据校验
    try:
        category_id = int(category_id)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数格式错误！')

    # 3.判断参数的值
    filters = [News.status == 0]
    # 如果分类id不为1，那么添加分类id的过滤
    if category_id != 1:
        filters.append(News.category_id == category_id)

    # 4.从数据库中查询
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
        # 获取查询出来的数据
        items = paginate.items
        # 获取到总页数
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    news_li = []
    for news in items:
        news_li.append(news.to_basic_dict())

    data = {
        "total_page":total_page,
        "current_page":current_page,
        "news_li":news_li
    }

    # 5.返回给前端渲染
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@index_blu.route('/')
@user_login_data
def index():
    """模板渲染
    1.如果用户登录，将当前登录用户信息，传到模板中
    :return:
    """
    user = g.user

    # 右侧点击排行模板渲染
    # 取出按浏览量从高到底顺序的数据
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_dict())

    # 获取新闻分类信息
    categories = Category.query.all()
    category_list = []
    for category in categories:
        category_list.append(category.to_dict())

    data = {
        "user": user.to_dict() if user else None,
        "news_dict_list":news_dict_list,
        "category_list":category_list
    }

    return render_template('news/index.html', data=data)


# 打开网页时，浏览器自动去请求根路径下favction.ico作为网站小图标
# send_static_file是flask去查找指定静态文件所调用的方法
@index_blu.route('/favicon.ico')
def favicon():
    # current_app应用上下文
    return current_app.send_static_file('news/favicon.ico')